package com.wngbms._05;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpServer03 {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

        ServerSocket serverSocket = new ServerSocket(8083);
        while (true) {
            Socket socket = serverSocket.accept();
            executorService.submit(() -> {
                try {
                    service(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void service(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();

        PrintWriter printWriter = new PrintWriter(outputStream, true);
        printWriter.println("HTTP/1.1 200 OK");
        printWriter.println("Content-Type:text/html;charset=utf-8");

        String body = "Windows 11" + Thread.currentThread().getName();
        printWriter.println("Content-Length:" +body.getBytes(StandardCharsets.UTF_8).length);
        printWriter.println();
        printWriter.println(body);

        printWriter.close();
        socket.close();
    }
}
